// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package importer

import (
	"context"
	"fmt"
	"os"

	"github.com/GoogleCloudPlatform/healthcare-data-protection-suite/internal/terraform"
	"github.com/ryanuber/columnize"
	billingbudgets "google.golang.org/api/billingbudgets/v1beta1"
)

// BillingBudget defines a struct with the necessary information for a google_billint_budget to be imported.
type BillingBudget struct{}

// ImportID returns the ID of the resource to use in importing.
func (i *BillingBudget) ImportID(rc terraform.ResourceChange, pcv ConfigMap, interactive bool) (string, error) {
	// Can't import if not interactive, since budget names are system-generated and will never be in the plan.
	if !interactive {
		return "", &InsufficientInfoErr{[]string{"budget"}, "Budget name is system-generated and will never be in the plan"}
	}

	billingAccountI, err := fromConfigValues("billing_account", rc.Change.After, pcv)
	if err != nil {
		return "", err
	}
	billingAccount := fmt.Sprintf("%s", billingAccountI)

	// The name is not set, it is autogenerated by the system.
	// Try to find existing budgets to offer as choices.
	budgets, err := i.getBudgets(billingAccount)
	if err != nil {
		return "", err
	}

	if len(budgets) <= 0 {
		// There are no budgets, just return that it doesn't exist so it can be created.
		return "", &DoesNotExistErr{rc.Address}
	}

	// Present the choices, if any.
	// Format the budgets more nicely.
	budgetsLines := []string{"Name|Display Name"}
	for _, budget := range budgets {
		budgetsLines = append(budgetsLines, fmt.Sprintf("%v|%v", budget.Name, budget.DisplayName))
	}

	prompt := fmt.Sprintf("Found the following budgets in billing account %v (copy the full value from the \"Name\" column):\n%s", billingAccount, columnize.SimpleFormat(budgetsLines))

	// Get the value from the user
	budget, err := fromUser(os.Stdin, "budget", prompt)
	if err != nil {
		return "", err
	}

	// From https://github.com/googleapis/google-api-go-client/blob/7c0994ebca7fbbc06ddfb19a468563437f8ec040/billingbudgets/v1beta1/billingbudgets-gen.go#L249
	// Values are of the form `billingAccounts/{billingAccountId}/budgets/{budgetId}`.
	return fmt.Sprintf("%v", budget), nil
}

func (i *BillingBudget) getBudgets(billingAccount string) (budgets []*billingbudgets.GoogleCloudBillingBudgetsV1beta1Budget, err error) {
	ctx := context.Background()
	service, err := billingbudgets.NewService(ctx)
	if err != nil {
		return budgets, err
	}

	budgetsService := billingbudgets.NewBillingAccountsBudgetsService(service)

	// For the format, see:
	// https://github.com/googleapis/google-api-go-client/blob/7c0994ebca7fbbc06ddfb19a468563437f8ec040/billingbudgets/v1beta1/billingbudgets-gen.go#L1252-L1258
	listCall := budgetsService.List(fmt.Sprintf("billingAccounts/%v", billingAccount))

	// Do the call repeatedly, as long as there are more pages.
	for {
		resp, err := listCall.Do()
		if err != nil {
			return budgets, err
		}
		budgets = append(budgets, resp.Budgets...)
		if resp.NextPageToken == "" {
			// No more pages, break out.
			break
		}
		listCall.PageToken(resp.NextPageToken)
	}

	return budgets, nil
}
